package com.zy.dao.impl;

import com.zy.dao.GetCarDao;
import com.zy.entity.Car;
import com.zy.utils.JdbcUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class GetCarDaoImpl implements GetCarDao {

    @Override
    public List<Car> getCarItems(int userId) {
        List<Car> carItems = new ArrayList<>();
        String sql = "SELECT c.shop_id, c.quantity, c.total_price, s.name, s.image_url, c.unit_price FROM tb_car c JOIN tb_shops s ON c.shop_id = s.id WHERE c.user_id = ?";
        try (Connection connection = JdbcUtil.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            preparedStatement.setInt(1, userId);
            try (ResultSet resultSet = preparedStatement.executeQuery()) {
                while (resultSet.next()) {
                    Car car = new Car();
                    car.setShopId(resultSet.getInt("shop_id"));
                    car.setQuantity(resultSet.getInt("quantity"));
                    car.setTotalPrice(resultSet.getDouble("total_price"));
                    car.setShopName(resultSet.getString("name"));
                    car.setShopImageUrl(resultSet.getString("image_url"));
                    car.setUnitPrice(resultSet.getDouble("unit_price"));
                    carItems.add(car);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return carItems;
    }
}
